package Rbac.service.array;

import Rbac.domain.dto.DeptDto;
import Rbac.domain.entity.Dept;
import Rbac.domain.vo.DeptVo;
import Rbac.domain.vo.Result;
import Rbac.service.IDeptService;
import Rbac.service.IUsersService;

import java.util.Arrays;

/**
 * 业务部门模块
 */
 public class DeptService implements IDeptService {
     private static final int DATA_SIZE=100;
     private final Dept[] data=new Dept[DATA_SIZE+1];
     private int idCounter=1;
     private IUsersService usersService;
     private static IDeptService singleton;
     private DeptService(){
     }
     public static IDeptService getInstance(){
        if(singleton==null){
            singleton=new DeptService();
        }
        return singleton;
    }
     public DeptVo convertToVo(Dept dept){
        return new DeptVo(dept.id,dept.name,dept.phone);
    }
     public Dept createEntity(DeptDto dto, int id){
        Dept dept=new Dept(dto.name,dto.phone);
        dept.id=id;
        return dept;
    }
     public void updateEntity(DeptDto dto, Dept dept){
        dept.name=dto.name;
        dept.phone=dto.phone;
    }
    @Override
     public boolean existsById(int id){
        return id < 1 || id >= idCounter || data[id] == null;
    }
    @Override
     public Dept findById(int id){
        if(existsById(id)){
            return data[id];
        }
        else {
            return null;
        }
    }
    @Override
     public Result list(){
        DeptVo[] temp=new DeptVo[DATA_SIZE];
        int length=0;
        for (int i = 1; i < DATA_SIZE; i++) {
            if(data[i]!=null){
                temp[length++]=convertToVo(data[i]);
            }
        }
        return Result.success("查询成功！",Arrays.copyOf(temp,length));
    }
    @Override
     public Result create(DeptDto dto){
        if(idCounter>DATA_SIZE){
            return Result.failure("创建失败，超出数据存储容量！");
        }
        else {
            Dept dept=createEntity(dto, idCounter++);
            data[dept.id] = dept;
            return Result.success("创建成功！", null);
        }
    }
    @Override
     public Result update(DeptDto dto, int id){
        if(existsById(id)){
            return Result.failure("更新失败，部门不存在！");
        }
        Dept dept=data[id];
        updateEntity(dto,dept);
        return Result.success("更新成功！", null);
    }
    @Override
     public Result delete(int id){
        if(existsById(id)) {
            return Result.failure("删除失败，部门不存在！");
        }
        if(usersService==null){
            usersService=UsersService.getInstance();
        }
        if(usersService.deptInUse(id)){
            return Result.failure("删除失败，部门正在使用！");
        }
        data[id]=null;
        return Result.success("删除成功！", null);
    }
}
